import axios from 'axios'
import { ElMessage } from 'element-plus'

const http = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:63073',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  },
  withCredentials: true // 启用cookie传递
})

// 请求拦截器 - 无需处理token
http.interceptors.request.use(config => {
  return config
})

// 响应拦截器 - 基础错误处理
http.interceptors.response.use(
  response => {
    const res = response.data
    if ([1].includes(res.code)) {
      return res
    }
    if (res.msg === '未登录' || response.status === 401) {
      ElMessage.error('请先登录')
      window.location.href = '/login'
      return Promise.reject(new Error('未登录'))
    }
    ElMessage.error(res.msg || '请求失败')
    return Promise.reject(res)
  },
  error => {
    if (error.response?.status === 401) {
      window.location.href = '/login'
    }
    ElMessage.error(error.message || '网络错误')
    return Promise.reject(error)
  }
)

export const checkLoginStatus = async () => {
  try {
    const response = await http.get('/isLogin')
    return response.code === 1
  } catch (error) {
    return false
  }
}

export default http
